﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using CDB.LinqModel.Data;
using CDB.LinqData;
using CDB.LinqModel;

public partial class back_AddNews : System.Web.UI.Page
{
    #region Variable Declaration
    IDataRepository _dataObject = new DataRepository();
    New news;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                news = new New(_dataObject);
                news.Id = Convert.ToInt32(Request.QueryString["id"]);
                news.GetNewsById();

                if (!string.IsNullOrEmpty(news.Title))
                {
                    txtNewsTitle.Text = news.Title;
                    txtNewsContent.InnerHtml = news.Description;
                }
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        news = new New(_dataObject);
        news.Title = txtNewsTitle.Text;
        news.Description = txtNewsContent.InnerHtml;

        if (checkIfNewsExists(news.Title))
        {
            divMessage.InnerHtml = "<strong>On snap!</strong>&nbsp;News with the same name Exists!";
            divMessage.Attributes.Add("class", "alert alert-error");
        }
        else
        {
            if (string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                news.Create();
                divMessage.InnerHtml = "<strong>Well done!</strong>&nbsp;News inserted successfully!";
                divMessage.Attributes.Add("class", "alert alert-success");
            }
            else
            {
                news.Id = Convert.ToInt32(Request.QueryString["id"]);
                news.Update();
                divMessage.InnerHtml = "<strong>Well done!</strong>&nbsp;News updated successfully!";
                divMessage.Attributes.Add("class", "alert alert-success");
            }
            clearFields();
        }
        
    }
    private bool checkIfNewsExists(string newsTitle)
    {
        New news = new New(_dataObject);
        news.Title = newsTitle;
        news.GetNewsByTitle();

        if (news.Id != 0)
            return true;
        else
            return false;
    }
    private void clearFields()
    {
        txtNewsTitle.Text = "";
        txtNewsContent.InnerText = "";
    }
}